package com.nononsenseapps.feeder.util;

import java.net.HttpURLConnection;
import java.net.URL;

public class LinkProtocolUtil {
    private final  static String HTTP= "http://";
    private final  static  String HTTPS =  "https://";

    //判断协议 能连接上则协议正确
    public  static String getProtocol(String url) {
        String newurl = clearUrl(url);
        url = HTTP + newurl;
        if (exists(url)) {
            return url;
        } else {
            url = HTTPS + newurl;
            if (exists(url)) {
                return url;
            } else {
                return null;
            }
        }
    }

    public static  String clearNoHeadUrl(String url) {
        if (url==null||url.startsWith(HTTP)||url.startsWith(HTTPS)||url.startsWith(HTTP.toUpperCase())||url.startsWith(HTTPS.toUpperCase())) {
            return url;
        }else
            for (int i = 0; i < url.length(); i++) {
                if (url.charAt(i) == '/' || url.charAt(i) == '.'|| url.charAt(i) == '\\') {
                } else {
                   url = url.substring(i);
                   break;
                }
            }
        return HTTP+url;
    }

    //清除URL里多余的符号
    public static  String clearUrl(String url) {
        if (url.contains(HTTP)) {
            url = url.substring(url.lastIndexOf(HTTP) + HTTP.length());
            for (int i = 0; i < url.length(); i++) {
                if (url.charAt(i) == '/' || url.charAt(i) == '.'
                        || url.charAt(i) == '\\') {
                } else {
                    url = url.substring(i);
                    return url;
                }
            }
        } else if (url.contains(HTTPS)) {
            url = url.substring(url.lastIndexOf(HTTPS) + HTTPS.length());
            for (int i = 0; i < url.length(); i++) {
                if (url.charAt(i) == '/' || url.charAt(i) == '.'
                        || url.charAt(i) == '\\') {
                } else {
                    url = url.substring(i);
                    return url;
                }
            }
        }else{
            if(url.startsWith("////"))
                url=url.substring(2);
            for (int i = 0; i < url.length(); i++) {
                if (url.charAt(i) == '/' || url.charAt(i) == '.'
                        || url.charAt(i) == '\\') {
                } else {
                    url = url.substring(i);
                    return url;
                }
            }
        }
        return url;
    }
    //是否能连接上
    private static boolean exists(String url) {
        try {
            HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection();
            con.setConnectTimeout(3000);
            return (con.getResponseCode() == 200);
        } catch (Exception e) {
            return false;
        }
    }

}
